#include "weather_forecast.h"
#include "ui_weather_forecast.h"
#include <QDebug>
#include <QMenu>
#include <QAction>

#include <QIcon>//信号通道
#include <QDate>//日期


WeatherForecast::WeatherForecast(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::WeatherForecast)
{
    ui->setupUi(this);
    // 去除标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint);
    // 设置无边框
    setWindowFlags(Qt::FramelessWindowHint);
    // 背景透明
    setAttribute(Qt::WA_TranslucentBackground);
    setFixedSize(750, 500); // 固定窗口大小

    // 初始化温度数组（默认值）
    int default_h[7] = {10 , 10 , 10 , 10 , 10 , 10 , 10};
    int default_l[7] = {0 , 0 , 0 , 0 , 0 , 0 , 0};
    memcpy(h_temp, default_h, sizeof(default_h));
    memcpy(l_temp, default_l, sizeof(default_l));

    ui->label->set_temp(h_temp);
    ui->label->set_high_low_temp(1);
    ui->label_2->set_temp(l_temp);
    ui->label_2->set_high_low_temp(0);

    // 创建搜索图标动作
    QAction *searchAction = new QAction(QIcon(":/搜索"), "", this);
    // 将图标添加到搜索框左侧
    ui->lineEdit->addAction(searchAction, QLineEdit::LeadingPosition);

        // 获取当前日期
        QDate currentDate = QDate::currentDate();
        // 获取星期几（返回值：1=星期一，7=星期日）
        int dayOfWeek = currentDate.dayOfWeek();

        // 根据数字映射为星期文本
        QString weekText;
        switch (dayOfWeek)
        {
            case 1: weekText = "星期一"; break;
            case 2: weekText = "星期二"; break;
            case 3: weekText = "星期三"; break;
            case 4: weekText = "星期四"; break;
            case 5: weekText = "星期五"; break;
            case 6: weekText = "星期六"; break;
            case 7: weekText = "星期日"; break;
            default: weekText = ""; // 异常情况
        }
        // 格式化当前日期为“年-月-日”，并拼接星期
        QString dateText = QString("%1年%2月%3日")
            .arg(currentDate.year())
            .arg(currentDate.month())
            .arg(currentDate.day());

        // 设置到label_5，格式为“今天的日期+星期几”
        ui->label_5->setText(dateText+weekText);

        ui->label_6->setText("今天"); // 设置到label_6
        ui->label_7->setText("明天"); // 设置到label_7
        ui->label_8->setText("后天"); // 设置到label_8

        // 后面4天显示为“X月X号”格式（例如10月12号）
            // 计算并设置第3天到第6天的日期
            ui->label_9->setText(QString("%1月%2号")
                .arg(currentDate.addDays(3).month())
                .arg(currentDate.addDays(3).day()));

            ui->label_10->setText(QString("%1月%2号")
                .arg(currentDate.addDays(4).month())
                .arg(currentDate.addDays(4).day()));

            ui->label_11->setText(QString("%1月%2号")
                .arg(currentDate.addDays(5).month())
                .arg(currentDate.addDays(5).day()));

            ui->label_12->setText(QString("%1月%2号")
                .arg(currentDate.addDays(6).month())
                .arg(currentDate.addDays(6).day()));


        // 关联搜索框输入完成事件到最高温度标签的槽函数
        connect(ui->lineEdit, &QLineEdit::editingFinished,
               this, &WeatherForecast::on_label_3_linkActivated);
        // 关联搜索框输入完成事件到最低温度标签的槽函数
        connect(ui->lineEdit, &QLineEdit::editingFinished,
                    this, &WeatherForecast::on_label_4_linkActivated);

        // 初始化网络访问管理器
        manager = new QNetworkAccessManager(this);

        // 初始化天气标签容器
        weatherLabels << ui->label_14 << ui->label_15 << ui->label_16
                      << ui->label_17 << ui->label_18 << ui->label_19 << ui->label_20;
}


WeatherForecast::~WeatherForecast()
{
    delete ui;
}

// 绘图事件
void WeatherForecast::paintEvent(QPaintEvent *event)
{
    // 准备画布
    QPainter Paint(this);

    // 准备画笔
    QPen pen;
    // 准备画刷
    QBrush brush;

    // 设置画笔
    pen.setColor(QColor(240,249,255 ));
    pen.setStyle(Qt::SolidLine);
    pen.setWidthF(0.1);

    // 设置画刷
    brush.setColor(QColor( 240 , 249 , 255  ));
    brush.setStyle(Qt::SolidPattern);

    // 为画布设置画笔画刷
    Paint.setPen(pen);
    Paint.setBrush(brush);

    // 绘制
    Paint.drawRoundedRect(this->rect() , 8 , 8 );

}

//搜索框的槽
void WeatherForecast::on_lineEdit_editingFinished()
{
    QString cityName = ui->lineEdit->text().trimmed();
    if (cityName.isEmpty()) {
        qDebug() << "请输入城市名";
        return;
    }
    qDebug() << "\n开始查询城市：" << cityName;

    // 1. 从本地文件查询城市编号
    QString cityId = getCityIdFromFile(cityName);
    if (cityId.isEmpty()) {
        qDebug() << "获取城市编号失败";
        return;
    }
    qDebug() << "获取到城市编号：" << cityId;

    // 2. 使用城市编号请求天气数据
    QUrl weatherUrl(QString("http://t.weather.itboy.net/api/weather/city/%1").arg(cityId));
    QNetworkReply *weatherReply = manager->get(QNetworkRequest(weatherUrl));
    connect(weatherReply, &QNetworkReply::finished, this, [=]() {
        onWeatherReplyFinished(weatherReply);
    });
}
//输出"最高温度"的槽
void WeatherForecast::on_label_3_linkActivated()
{
    // 获取搜索框输入的内容
    QString inputText = ui->lineEdit->text().trimmed();

    // 拼接内容：输入内容 + 最高温度
    QString result_1 = inputText + "最高温度：";

    // 显示到“最高温度”标签自身
    ui->label_3->setText(result_1);
}
//输出"最低温度"的槽
void WeatherForecast::on_label_4_linkActivated()
{
    // 获取搜索框输入的内容
    QString inputText = ui->lineEdit->text().trimmed();

    // 拼接内容：输入内容 + 最低温度
    QString result_2 = inputText + "最低温度：";

    // 显示到“最低温度”标签自身
    ui->label_4->setText(result_2);
}

// 从 city.txt 中查询城市编号
QString WeatherForecast::getCityIdFromFile(const QString &cityName)
{
    QString filePath = ":/city.txt";//(文件的相对路径或者绝对路径)
    QFile file(filePath);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开城市文件：" << file.errorString();
        return "";
    }

    QTextStream in(&file);
    in.setCodec("UTF-8"); // 设置编码

    qDebug() << "开始读取文件内容：";
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        qDebug() << "读取到行：" << line; // 输出每行内容，检查是否正确

        if (line.isEmpty()) continue;

        QStringList parts = line.split('\t');
        qDebug() << "分割后：" << parts; // 查看分割结果

        if (parts.size() != 2) continue;

        QString id = parts[0].trimmed();
        QString name = parts[1].trimmed();

        if (name == cityName) {
            file.close();
            return id;
        }
    }

    file.close();
    qDebug() << "未找到城市：" << cityName;
    return "";
}

void WeatherForecast::onWeatherReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug() << "天气请求失败：" << reply->errorString();
        reply->deleteLater();
        return;
    }

    // 解析天气数据
    QByteArray data = reply->readAll();
    reply->deleteLater();
    qDebug() << "天气接口返回原始数据：" << data;

    QJsonDocument doc = QJsonDocument::fromJson(data);
    if (doc.isNull()) {
        qDebug() << "天气数据解析失败：" << data;
        return;
    }

    QJsonObject root = doc.object();
    // 关键修正：status是整数类型，应转换为整数后判断
    int status = root["status"].toInt();
    if (status != 200) {
        qDebug() << "天气查询失败，状态码：" << status << "，信息：" << root["message"].toString();
        return;
    }

    // 提取城市信息
    QString cityName = root["cityInfo"].toObject()["city"].toString();
    qDebug() << "\n======" << cityName << "7天天气信息======";

        // 提取7天预报数据并转换为数值
        QJsonArray forecast = root["data"].toObject()["forecast"].toArray();
        int highTemps[7] = {0}; // 临时存储7天最高温
        int lowTemps[7] = {0};  // 临时存储7天最低温
        for (int i = 0; i < forecast.size() && i < 7; i++) {
            QJsonObject day = forecast[i].toObject();

            // 提取最高温：先移除"高温 "，再移除"℃"，只保留数字
            QString highStr = day["high"].toString();
            highStr.remove("高温 ").remove("℃");
            highTemps[i] = highStr.toInt();

            // 提取最低温：先移除"低温 "，再移除"℃"，只保留数字
            QString lowStr = day["low"].toString();
            lowStr.remove("低温 ").remove("℃");
            lowTemps[i] = lowStr.toInt();

            // 提取天气状况并赋值给weatherTypes
            weatherTypes[i] = day["type"].toString();

            // 打印到控制台
            qDebug() << QString("%1（%2）：%3，最低%4℃，最高%5℃")
                        .arg(day["ymd"].toString())
                        .arg(day["week"].toString())
                        .arg(day["type"].toString())
                        .arg(lowTemps[i])
                        .arg(highTemps[i]);
        }

        // 关键：将解析到的温度数据更新到h_temp和l_temp数组
        memcpy(h_temp, highTemps, sizeof(highTemps));  // 更新最高温数组
        memcpy(l_temp, lowTemps, sizeof(lowTemps));    // 更新最低温数组

        // 更新温度曲线（使用h_temp和l_temp数组）
        ui->label->set_temp(h_temp);    // 最高温曲线
        ui->label_2->set_temp(l_temp);  // 最低温曲线
        ui->label->update();
        ui->label_2->update();

        // 新增：更新天气情况到label14-20并设置图标
            // 1. 定义天气类型与图标资源的映射（根据实际资源文件名调整）
            QMap<QString, QString> weatherIconMap = {
                {"中雨", ":/中雨"},
                {"中雪", ":/中雪"},
                {"晴", ":/晴天"},
                {"阴", ":/阴天"},
                {"低温", "::/低温报警"},
                {"冰雹", ":/冰雹"},
                {"台风", ":/台风"},
                {"多云转晴", ":/多云转晴"},
                {"多云", ":/多云"},
                {"大雨", ":/大雨"},
                {"大雪", ":/大雪"},
                {"小雨", ":/小雨"},
                {"小雪", ":/小雪"},
                {"霾", ":/霾"},
                {"晴转多云", ":/晴转多云"},
                {"暴风雪", ":/暴风雪"},
                {"沙尘暴", ":/沙尘暴"},
                {"雷阵雨", ":/雷阵雨"},
                {"雾", ":/雾天"},
                {"霜冻", ":/霜冻"},
                {"高温", ":/高温报警"},
                // 可根据实际天气类型扩展
            };

            // 2. 将label14-label20存入数组，方便批量处理
            QLabel* weatherLabels[7] =
            {
                ui->label_14,
                ui->label_15,
                ui->label_16,
                ui->label_17,
                ui->label_18,
                ui->label_19,
                ui->label_20
            };

            // 3. 遍历7天数据，设置每个label的图标和文本
            for (int i = 0; i < 7; i++) {
                    QLabel* currentLabel = weatherLabels[i];
                    if (!currentLabel) continue;

                    currentLabel->clear();

                    // 创建水平布局，用于放置图标和文本标签
                    QHBoxLayout* layout = new QHBoxLayout(currentLabel);
                    currentLabel->setLayout(layout);

                    // 图标标签
                    QLabel* iconLabel = new QLabel(currentLabel);
                    QString iconPath = weatherIconMap.value(weatherTypes[i], ":/icons/default.png");
                    iconLabel->setPixmap(QIcon(iconPath).pixmap(32, 32)); // 设置图标大小，可根据需求调整
                    iconLabel->setAlignment(Qt::AlignCenter);

                    // 文本标签
                    QLabel* textLabel = new QLabel(weatherTypes[i], currentLabel);
                    textLabel->setAlignment(Qt::AlignCenter);

                    layout->addWidget(iconLabel);
                    layout->addWidget(textLabel);
                    layout->setContentsMargins(0, 0, 0, 0); // 去除布局边距
                }
}
